import { TextureLoader } from "three"
import { EventEmitter } from "./EventEmitter"
import {StaticGroup} from "../../model";
import geoJson_full from '../../json/geoJson_full.json'
export class Resource extends EventEmitter {
  itemsLoaded:any;
  assets:any;
  loader:any;

  constructor({ dracoPath=null } = {}) {
    super()

    this.itemsLoaded = 0
    this.assets = []
    this.loader=new TextureLoader();
  }

  // loadItem(item) {
  //   if (item.type==='Texture'){
  //     const texture=this.loader.load(item.path)
  //     return ({ ...item, data:texture })
  //   }else if (item.type==='File'){
  //     if (item.path=='geoJson'){
  //       return ({ ...item, data:JSON.stringify(geoJson_full) })
  //     }else{
  //       const geoJson = $.ajax({url: item.path, async: false}).responseText;
  //       return ({ ...item, data:geoJson })
  //     }
  //   }
  //   return {}
  // }


  // loadItem(item) {
  //   if (item.type === 'Texture') {
  //     const texture = this.loader.load(item.path)
  //     return ({...item, data: texture})
  //   } else if (item.type === 'File') {
  //     let para = StaticGroup.paraData;
  //     if (item.name != 'areaInfo') {
  //       para = {
  //         "level": 1,
  //         "conditions": [
  //           "world/中国"
  //         ]
  //       }
  //     }
  //     const geoJson = $.ajax({url: `map/${para["conditions"][0]}-area.json`, async: false}).responseText;
  //     return ({...item, data: geoJson})
  //   }
  //   return {}
  // }

  loadItem(item) {
    if (item.type === 'Texture') {
      const texture = this.loader.load(item.path)
      return ({...item, data: texture})
    } else if (item.type === 'File') {
      const para = StaticGroup.paraData;
      if (item.path == 'geoJson' || para["conditions"][0]=="world/中国") {
        return ({ ...item, data:JSON.stringify(geoJson_full) })
      } else {
        const geoJson = this.HttpPost(para);
        return ({...item, data: geoJson})
      }
    }
    return {}
  }

  HttpPost(para){
    const xhr = new XMLHttpRequest();
    const url="/api/dashboards/Map/GeoData";

    xhr.open('POST', url, false);
    xhr.setRequestHeader('Content-Type', 'application/json');

    xhr.send(JSON.stringify(para));
    // 处理响应
    if (xhr.status === 200) {
      return JSON.stringify(JSON.parse(xhr.responseText));
    } else {
      return null;
    }
  }

  loadAll(assets) {
    this.itemsLoaded = 0
    return new Promise((resolve, reject) => {
      let currentAssets = this.matchType(assets);
      let promise = [] as any;
      currentAssets.map((item) => {
        let currentItem = this.loadItem(item)
        promise.push(currentItem)
      })
      Promise.all(promise)
          .then((res) => {
            this.assets = res
            this.emit("onLoad")
            resolve(res)
          })
          .catch((err) => {
            this.emit("onError", err)
            reject(err)
          })
    })
  }

  matchType(assets) {
    return assets.map((item) => {
      return {
        type: item.type,
        path: item.path,
        name: item.name,
        data: null,
      }
    });
  }

  getResource(name) {
    let current = this.assets.find((item) => {
      return item.name === name.toString()
    })
    if (!current) {
      throw new Error(`资源${name}不存在`)
    }
    return current.data
  }
  destroy() {
    this.off("onProgress",{})
    this.off("onLoad",{})
    this.off("onError",{})
    this.assets = []
  }
}
